package controllers;

import play.data.Form;
import play.db.jpa.Transactional;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.*;
import controllers.service.LoginService;

public class Application extends Controller {

	// -- Authentication
	public static class Login {
		public String username;
		public String password;
	}

	@Transactional
	public static Result index() {

		if (session("connected") != null) {
			return ok(index.render());
		} else {
			return redirect("/login");
		}

	}

	@Transactional
	public static Result login() {
		return ok(login.render());
	}

	@Transactional
	public static Result authenticate() {
		Form<Login> loginForm = Form.form(Login.class).bindFromRequest();

		LoginService service = new LoginService();

		if (service.validateLogin(loginForm.get().username,
				loginForm.get().password)) {
			session("connected", loginForm.get().username);
			return redirect(routes.Application.index());
		} else {
			return badRequest(login.render());
		}
	}

	@Transactional
	public static Result logout() {
		session().remove("connected");
		return redirect(routes.Application.login());
	}

	@Transactional
	public static Result register() {

		return ok(register.render());
	}
}
